package com.smartwasser.yunhtgl.apphtgl.function;

import android.app.Dialog;
import android.graphics.Canvas;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

import com.joanzapata.pdfview.PDFView;
import com.joanzapata.pdfview.listener.OnDrawListener;
import com.joanzapata.pdfview.listener.OnLoadCompleteListener;
import com.joanzapata.pdfview.listener.OnPageChangeListener;
import com.smartwasser.yunhtgl.apphtgl.R;
import com.smartwasser.yunhtgl.apphtgl.base.BaseActivity;
import com.smartwasser.yunhtgl.apphtgl.utils.Logger;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.dou361.dialogui.DialogUIUtils.dismiss;
import static com.smartwasser.yunhtgl.apphtgl.R.id.pdf_reader;
import static com.smartwasser.yunhtgl.apphtgl.network.Retrofits.base;

/**
 * PDF阅读尝试
 */
public class PdfReader extends BaseActivity implements OnPageChangeListener, OnLoadCompleteListener, OnDrawListener {
    private Handler mHandler = new Handler();
    private Dialog loadingHorizontal;
    private String FilePath;
    @BindView(pdf_reader)
    PDFView pdfView;
    @BindView(R.id.tv_toolbar)
    TextView tv_toolbar;

    @Override
    public void setContentLayout() {
        setContentView(R.layout.read_pdf);
        ButterKnife.bind(this);
    }

    @Override
    public void initView() {
        tv_toolbar.setText("PDF阅读");
        FilePath = base + getIntent().getStringExtra("FilePath");
        //FilePath = file + getIntent().getStringExtra("FilePath");
        Logger.e("FilePath = " + FilePath);
    }

    @Override
    public void initData() {
        loadingHorizontal = showLoadingHorizontal(this, "加载PDF...").show();
        new Thread() {
            @Override
            public void run() {
                displayFromFile(new File(FilePath));
            }
        }.start();
    }

    @OnClick({R.id.back})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
        }
    }

    private void displayFromFile(final File file) {
        try {
            pdfView.fromFile(file).defaultPage(1).onPageChange(this).onLoad(this).onDraw(this).showMinimap(true).swipeVertical(false).enableSwipe(true).load();
        } catch (Exception e) {
            dismiss(loadingHorizontal);
        }
    }

    @Override
    public void loadComplete(int nbPages) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                dismiss(loadingHorizontal);
            }
        }, 5000);
    }

    @Override
    public void onPageChanged(int page, int pageCount) {

    }

    @Override
    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {

    }
}